/*******************************************************************************
 * Copyright 2018 The MIT Internet Trust Consortium
 *
 * Portions copyright 2011-2013 The MITRE Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package org.mitre.openid.connect.service.impl;

import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTClaimsSet;
import org.mitre.jwt.signer.service.JWTSigningAndValidationService;
import org.mitre.oauth2.model.ClientDetailsEntity;
import org.mitre.oauth2.model.ClientDetailsEntity.SubjectType;
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
import org.mitre.oauth2.service.ClientDetailsEntityService;
import org.mitre.openid.connect.config.ConfigurationPropertiesBean;
import org.mitre.openid.connect.dto.UserDto;
import org.mitre.openid.connect.model.UserInfo;
import org.mitre.openid.connect.repository.UserInfoRepository;
import org.mitre.openid.connect.repository.impl.JpaUserInfoRepository;
import org.mitre.openid.connect.service.PairwiseIdentiferService;
import org.mitre.openid.connect.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Implementation of the UserInfoService
 *
 * @author Michael Joseph Walsh, jricher
 *
 */
@Service
public class DefaultUserInfoService implements UserInfoService {

	@Autowired
	private UserInfoRepository userInfoRepository;

	@Autowired
	private ClientDetailsEntityService clientService;

	@Autowired
	private PairwiseIdentiferService pairwiseIdentifierService;

	@Override
	public UserInfo getByUsername(String username) {

		return userInfoRepository.getByUsername(username);
	}

	@Override
	public UserInfo getByUsernameAndClientId(String username, String clientId) {

		ClientDetailsEntity client = clientService.loadClientByClientId(clientId);

		UserInfo userInfo = getByUsername(username);

		if (client == null || userInfo == null) {
			return null;
		}
		userInfo.setSub(userInfo.getPreferredUsername());
		if (SubjectType.PAIRWISE.equals(client.getSubjectType())) {
			String pairwiseSub = pairwiseIdentifierService.getIdentifier(userInfo, client);
			//userInfo.setSub(pairwiseSub);
		}

		return userInfo;

	}

	@Override
	public UserInfo getByEmailAddress(String email) {
		return userInfoRepository.getByEmailAddress(email);
	}



	@Autowired
	private JpaUserInfoRepository jpaUserInfoRepository;
	@Autowired
	private JWTSigningAndValidationService jwtService;
	private static final String CLIENT_ID = "client";
	private static final String KEY_ID = "key";
	private ConfigurationPropertiesBean configBean = new ConfigurationPropertiesBean();
	private ClientDetailsEntity client = new ClientDetailsEntity();
	private OAuth2AccessTokenEntity accessToken = new OAuth2AccessTokenEntity();
	private OAuth2Request request = new OAuth2Request(CLIENT_ID) { };
	private void configure(DefaultOIDCTokenService s) {
		s.setConfigBean(configBean);
		s.setJwtService(jwtService);
		s.setJpaUserInfoRepository(jpaUserInfoRepository);
	}
	@Override
	public JWT getTokenByDingUser(String dingUserId) {
		configBean.setIssuer("https://auth.example.org/");
		UserDto user=jpaUserInfoRepository.getUserByDingId(dingUserId);
		if(user!=null){
			client.setClientId(CLIENT_ID);
			client.setUserId(user.getId());
			client.setUserCode(user.getUserCode());
			client.setUserName(user.getUserName());
			DefaultOIDCTokenService s = new DefaultOIDCTokenService() {
				@Override
				protected void addCustomIdTokenClaims(JWTClaimsSet.Builder idClaims, ClientDetailsEntity client, OAuth2Request request,
													  String sub, OAuth2AccessTokenEntity accessToken) {
					idClaims.claim("test", "foo");
				}
			};
			configure(s);

			JWT token = s.createIdToken(client, request, new Date(), user.getUserCode(), accessToken);
			return token;
		}else{
			return null;
		}
	}

}
